<template>
	<view>
		<tn-modal v-model="scopeShow" :custom="true">
			<view class="custom-modal-content tn-flex tn-flex-direction-column" style="height: 200rpx;">
				<view class="tn-flex-2 tn-flex tn-flex-row-center tn-flex-col-center">
					此小程序将获取你的手机号,头像,昵称等
				</view>
				<view class="tn-flex-1 tn-flex tn-flex-row-between tn-flex-col-center">
					<button @click="Cancel" class="tn-flex-1" style="background-color: #fff;">取消</button>
					<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" class="tn-flex-1"
						style="background-color: #fff;" @click="getLogin">确认</button>
				</view>
			</view>
		</tn-modal>
	</view>
</template>

<script>
	import {
		resphoneApi,
		addUserApi
	} from '../../apis/indexApi.js'
	export default {
		name: "PopUps",
		data() {
			return {
				scopeShow: false,
				loginResCode: ''
			};
		},
		mounted() {
			if (!uni.getStorageSync('user').openid) {
				this.scopeShow = true;
			}
			if (!uni.getStorageSync('user').latitude) {
				this.getAddressScope();
			}
		},
		// props: ["scopeShow"],
		methods: {
			Cancel() {
				uni.clearStorageSync();
				uni.navigateTo({
					url: '/pages/index/index'
				});
				this.scopeShow = false;
			},
			getLogin() {
				// uni.showLoading({
				// 	title: '加载中'
				// });
				let _this = this;
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						if (loginRes.errMsg == 'login:ok') {
							_this.loginResCode = loginRes.code;
						}
					}
				});
				// uni.getUserProfile({
				// 	desc: '1312312',
				// 	success: res => {
				// 		// _this.user.name = res.userInfo.nickName;
				// 		// _this.user.avatarUrl = res.userInfo.avatarUrl;
				// 		let user = uni.getStorageSync('user') || {};
				// 		user.name = res.userInfo.nickName;
				// 		user.avatarUrl = res.userInfo.avatarUrl;
				// 		uni.setStorageSync('user', user);
				// 		// uni.hideLoading();
				// 		// fun && fun();
				// 	},
				// 	fail: res => {
				// 		//拒绝授权
				// 		// uni.hideLoading();
				// 		return;
				// 	}
				// });
				// let user = uni.getStorageSync('user') || {};
				// // user.name = res.userInfo.nickName;
				// user.avatarUrl = res.userInfo.avatarUrl;
				// uni.setStorageSync('user', user);
			},
			getAddress() {
				let _this = this;
				uni.showLoading({
					title: '加载中'
				});
				// console.log(111)
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: (res) => {
						// console.log('当前位置的经度：' + res.longitude);
						// console.log('当前位置的纬度：' + res.latitude);
						let user = uni.getStorageSync('user') || {};
						user.longitude = res.longitude;
						user.latitude = res.latitude;
						uni.setStorageSync('user', user);
						uni.request({
							header: {
								"Content-Type": "application/text"
							},
							url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' +
								res.latitude + ',' + res.longitude +
								'&key=DSJBZ-SGIEP-S5RDM-LNEZN-LTRH3-MRBA4',
							success(re) {
								if (re.statusCode === 200) {
									// _this.address = re.data.result.address;
									uni.setStorageSync('address', re.data.result.address);
									// _this.province = re.data.result.address.slice(re.data.result
									// 	.address.indexOf('省') + 1,
									// 	re.data.result.address.indexOf('市') + 1);
									// _this.isDenlu++;
								} else {
									_this.$t.message.toast("获取位置失败")
								}
								uni.hideLoading();
							}
						});
					}
				});
			},
			getPhone(code, encryptedData, iv) {
				resphoneApi({
					code,
					encryptedData,
					iv
				}).then(res => {
					// console.log(res)
					if (res.data.code == 200) {
						addUserApi({
							phone: res.data.data.phoneNumber,
							openid: res.data.openid
						}).then(results => {
							if (results.data.msg == '添加成功') {
								// console.log(results)
								const user = uni.getStorageSync('user') || {};
								user.u_id = results.data.u_id;
								user.openid = res.data.openid;
								user.phone = res.data.data.phoneNumber;
								user.appid = res.data.data.watermark.appid;
								// user.userType = results.data.type;
								uni.setStorageSync('user', user);
								uni.hideLoading();
								this.scopeShow = false;
								// this.isDenlu++;
							}
						}).catch(err => {
							console.log(err)
						})
					} else {
						console.log('获取解密后的手机号失败', res.data.obj)
						uni.showToast({
							title: '获取手机失败，请重试',
							icon: 'none',
							duration: 1500,
						})
					}
				}).catch(err => {
					console.log(err)
				})

			},
			getPhoneNumber(ev) {
				uni.showLoading({
					title: '加载中'
				});
				let that = this;
				if (ev.detail.errMsg == 'getPhoneNumber:fail user deny') {
					console.log('用户拒绝提供手机号');
				} else {
					// console.log('用户同意提供手机号');
					// console.log("iv", ev.detail.iv)
					// console.log("encryptedData", ev.detail.encryptedData)
					let encryptedData = ev.detail.encryptedData
					let iv = ev.detail.iv

					//检查登录
					uni.checkSession({
						success: (res) => {
							console.log("checkSession--success---res", res)
							if (res.errMsg == 'checkSession:ok') {
								console.log(res);
								console.log('登录暂未过期');
								if (encryptedData !== undefined && iv !== undefined) {
									that.getPhone(that.loginResCode, encryptedData, iv)
								}
							}
						},
						fail: (res) => {
							// console.log("checkSession---fail---res", res)
							console.log('登录已过期');
							//再执行一次login
							uni.login({
								provider: 'weixin',
								success: function(loginRes) {
									// console.log("loginRes.code", loginRes.code);
									that.loginResCode = loginRes.code;

									if (encryptedData !== undefined && iv !== undefined) {
										that.getPhone(that.loginResCode, encryptedData, iv)
									}
								}
							});
						}
					})
				}
			},
			getAddressScope() {
				let _this = this;
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.userLocation']) {
							// 未授权
							uni.authorize({
								scope: 'scope.userLocation',
								success() { //1.1 允许授权
									_this.getAddress();
								},
								fail() { //1.2 拒绝授权
									console.log("你拒绝了授权，无法获得周边信息")
								}
							})
						} else {
							_this.getAddress();
						}
					}
				});
			},
		}
	}
</script>

<style lang="scss">

</style>
